package model;

import java.util.Calendar;

import util.IDGenerator;

import Repository.Repository;
import Repository.RepositoryFactory;
import constants.SMSConstants;
import factory.SMSObjectFactory;

public class Qualified implements SMSObjectState
{
	private final String NAME = "Qualified";
	
	RuleSelector ruleSelector;
	NextStateCalculator stateCalculator;
	CalculateNextStateStrategy strategy;
	Repository repository;

	
	@Override
	public void execute(SMSObject smsObj) {
		if(smsObj instanceof Lead){
			//System.out.println("Executing Qualified State...");
		    ruleSelector =  new ImportRuleSelector(smsObj);
			//Rule rule = ruleSelector.getRule();
			stateCalculator = new NextStateCalculator();						
			SMSObjectState newState = stateCalculator.getNextState(smsObj,ruleSelector);
			//System.out.println("New state..." + newState.getStateName());
			
			if(newState.getStateName().equals(NAME)){
				System.out.println("****Lead cannot be imported as the object doesnot comply to the rules****");
				return;
			}
			
		//	System.out.println("Creating new opportunity object..." );
			Lead l = (Lead)smsObj;
			SMSObjectFactory factory = new SMSObjectFactory();
			Opportunity opportunity = (Opportunity)factory.createSMSObject(SMSConstants.OPPORTUNITY);
			long id = IDGenerator.getNextId();
			opportunity.setSmsObjId(id);			
			opportunity.setAccount(l.getAccount());
			Calendar cal = Calendar.getInstance();
			cal.set(l.getLeadDate().getYear(), l.getLeadDate().getMonth(), l.getLeadDate().getDate());
			cal.add(Calendar.DATE,30);
			opportunity.setClosedDate(cal.getTime());
			opportunity.setDescription(l.getProductInterest());
			opportunity.setProductName(l.getProductInterest());
			opportunity.setName(l.getName());
			opportunity.setCurrentState(newState);
			opportunity.setManagedByUser(l.getManagedByUser());
			
			repository = RepositoryFactory.getRepository(SMSConstants.OPPORTUNITY);
			repository.insert(new Long(id),opportunity);
			//System.out.println("Creating new opportunity object..."+ id  + newState.getStateName());
			
			smsObj.setCurrentState(new Finalized());
			repository = RepositoryFactory.getRepository(SMSConstants.LEAD);
			repository.update(smsObj.getSmsObjId(), smsObj);
			System.out.println("Successfully imported opportunity.");
			
		}
		
	}
	
	public String getStateName(){
		return NAME;
	}
}
